package com.example.demo.leeCode;

import java.util.Arrays;

/**
 * 传入一个矩阵（二位数组）,顺时针打印并输出
 * 比如
 *  1,2,3
 *  4,5,6
 *  7,8,9
 *
 *  输出结果为
 *  1,2,3,6,9,8,7,4,5
 */
public class Matrix {

    public static void main(String[] args) {
        int [][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        int []array = new Matrix().getMatrix(matrix);
        System.out.println(Arrays.toString(array));
    }

    public int[] getMatrix(int[][] matrix){
        int index = 0, l = 0, r = matrix[0].length, t = 0, b = matrix.length;
        int length = matrix.length*matrix[0].length;
        int [] array = new int[r*b];
        while(index < length){
            // 从左到右
            for(int i=l; i<r; i++){
                array[index++] = matrix[t][i];
            }
            if(++t>b)
                break;

            //从上到下
            for(int i=t; i<b; i++){
                array[index++] = matrix[i][r-1];
            }
            if(l>--r)
                break;
            //从右到左
            for(int i=r-1; i>=l; i--){
                array[index++] = matrix[b-1][i];
            }
            if(t>--b)
                break;
            //从下到上
            for(int i=b-1; i>=t; i--){
                array[index++] = matrix[i][l];
            }
            if(++l>r){
                break;
            };
        }
        return array;
    }

}
